package com.example.studentregistration.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.studentregistration.mapper.UserMapper;
import com.example.studentregistration.pojo.Users;
import com.example.studentregistration.service.UserService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


//业务逻辑接口的实现类
@Service
public class UserServiceImpl implements UserService {
    //注入持久层接口
    @Autowired
    private UserMapper userMapper;

    //根据手机号查询用户信息
    @Override
    public Result<Users> queryUserByPhone(String phone) {
        Users users = userMapper.queryUserByPhone(phone);
        if (users != null) {
            return Result.success(users);
        }
        return Result.fail("该用户不存在");
    }

    //添加用户(先通过手机号查询用户信息，如果手机号不存在则添加用户，如果手机号存在则返回手机号已存在)
    @Override
    public Result<?> insertUser(Users user) {
        Users users = userMapper.queryUserByPhone(user.getPhone());
        if (users == null) {
            //系统生成时间
            user.setCreateTime(new Date());
            //将密码加密存储
            user.setPassword(new String(SecureUtil.md5(user.getPassword())));
            int result = userMapper.insertUser(user);
            if (result > 0) {
                return Result.success("添加成功");
            }
            return Result.fail("添加失败");
        }
        return Result.fail("手机号已存在");
    }

    //修改用户信息
    @Override
    public Result<?> updateUser(Users user) {
        // 仅当传入了明文密码时才进行加密更新；否则不更新密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(new String(SecureUtil.md5(user.getPassword())));
        } else {
            user.setPassword(null);
        }
        user.setUpdateTime(new Date());
        int result = userMapper.updateUser(user);
        if (result > 0) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败");
    }

    //删除用户
    @Override
    public Result<?> deleteUser(Integer id) {
        int result = userMapper.deleteUser(id);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    //分页查询所有用户
    @Override
    public Page queryAllUsers(Integer currentPage, Integer pageSize) {
        Page<Users> page = PageHelper.startPage(currentPage, pageSize);
        userMapper.queryAllUsers();
        return page;
    }

    //根据用户名查询用户信息
    @Override
    public Result<Users> queryUserByName(String username) {
        Users users = userMapper.queryUserByName(username);
        if (users != null) {
            return Result.success(users);
        }
        return Result.fail("该用户不存在");
    }

//    用户登录
    @Override
    public Result<?> login(String phone, String password) {
         Users user = userMapper.login(phone, new String(SecureUtil.md5(password)));
        System.out.println(phone);
        System.out.println(password);
        return user == null ? Result.fail("账号或密码错误") : Result.success(user);
    }

    //文件导出
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
//        1,查询所有用户信息
        List<Users> users = userMapper.queryAllUsers();
        ///2.通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //3.一次性写出内容，使用默认样式，强制输出标题
        writer.write(users, true);
        //设置浏览器响应格式
        //设置导出文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//获取输出流对象
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os, true);
// 关闭writer，释放内存
        writer.close();
//此处记得关闭输出Servlet流
        IoUtil.close(os);
    }

    //批量删除
    @Override
    public int batchDeleteUser(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        return userMapper.batchDeleteUser(ids);
    }

    // 新增：根据ID查询
    @Override
    public Result<Users> findById(Integer id) {
        Users user = userMapper.findById(id);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        return Result.success(user);
    }

    // 新增：修改密码（校验旧密码是否正确，再写入新密码MD5）
    @Override
    public Result<?> changePassword(Integer id, String oldPassword, String newPassword) {
        Users db = userMapper.findById(id);
        if (db == null) {
            return Result.fail("用户不存在");
        }
        String dbPwd = db.getPassword();
        if (dbPwd == null) {
            return Result.fail("旧密码不正确");
        }
        String oldMd5 = SecureUtil.md5(oldPassword);
        boolean oldMatch = oldPassword.equals(dbPwd) || oldMd5.equals(dbPwd);
        if (!oldMatch) {
            return Result.fail("旧密码不正确");
        }
        // 判断当前库中密码是否为MD5（32位十六进制），保持与原有存储一致
        boolean storedAsMd5 = dbPwd.matches("^[a-fA-F0-9]{32}$");
        String toSave = storedAsMd5 ? SecureUtil.md5(newPassword) : newPassword;
        int n = userMapper.updatePassword(id, toSave);
        return n > 0 ? Result.success("密码已更新") : Result.fail("密码更新失败");
    }

    // 新增：通过手机号重置密码（无需验证码，仅需手机号存在），重置为默认新密码：123456
    @Override
    public Result<?> resetPasswordByPhone(String phone) {
        Users db = userMapper.queryUserByPhone(phone);
        if (db == null) {
            return Result.fail("手机号未注册");
        }
        String defaultNew = "123456";
        String dbPwd = db.getPassword();
        // 按存储策略决定是否MD5
        boolean storedAsMd5 = dbPwd != null && dbPwd.matches("^[a-fA-F0-9]{32}$");
        String toSave = storedAsMd5 ? SecureUtil.md5(defaultNew) : defaultNew;
        int n = userMapper.updatePassword(db.getId(), toSave);
        return n > 0 ? Result.success("密码已重置为123456") : Result.fail("重置失败");
    }
}
